package com.bing.spring;

import com.bing.xml.Address;
import com.bing.xml.Person;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.core.io.ClassPathResource;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;

/**
 * Created by kaibb on 15-9-9.
 */
public class XmlPostProcesor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        ClassPathResource classPathResource = new ClassPathResource("conf/person.xml");
        JAXBContext jaxbContext = null;
        try {
            jaxbContext = JAXBContext.newInstance("com.bing.xml");
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            JAXBElement<Person> o = (JAXBElement<Person>) unmarshaller.unmarshal(classPathResource.getInputStream());
            Person p = o.getValue();

            BeanDefinitionRegistry registry = ((BeanDefinitionRegistry) beanFactory);

            GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
            beanDefinition.setBeanClass(Person.class);
            beanDefinition.setLazyInit(true);
            beanDefinition.setAbstract(false);
            beanDefinition.setAutowireCandidate(false);
            beanDefinition.getPropertyValues().add("name", p.getName());
            beanDefinition.getPropertyValues().add("age", p.getAge());
            RuntimeBeanReference runtimeBeanReference = new RuntimeBeanReference("address");
            beanDefinition.getPropertyValues().add("address", runtimeBeanReference);

            GenericBeanDefinition adress = new GenericBeanDefinition();
            adress.setBeanClass(Address.class);
            adress.setLazyInit(true);
            adress.setAbstract(false);
            adress.setAutowireCandidate(false);
            adress.getPropertyValues().add("name", "恩恩");


            registry.registerBeanDefinition("kaibing", beanDefinition);
            registry.registerBeanDefinition("address", adress);


            System.out.println(o);
        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
